package com.lzyyj.common;

import org.apache.commons.lang.ObjectUtils;

/**
 * 
 * 枚举工具类
 * 
 */
public abstract class EnumUtils {

	public synchronized static <T extends Enum<T>> T getEnumByName(Class<T> enumClass, String name){
		return fromEnumConstantName(enumClass, name);
	}
	
	public synchronized static <T extends Enum<T>> T getEnumByValue(Class<T> enumClass,Object value){
		return fromEnumProperty(enumClass, "value", value);
	}
	
	
	/**
	 * 从指定的枚举类中根据property搜寻匹配指定值的枚举实例
	 * 
	 * @param <T>
	 * @param enumClass
	 * @param property
	 * @param propValue
	 * @return
	 */
	private static <T extends Enum<T>> T fromEnumProperty(Class<T> enumClass, String property, Object propValue) {
		T result = null;

		T[] enumConstants = enumClass.getEnumConstants();

		for (T t : enumConstants) {
			Object constantPropValue;
			try {
				constantPropValue = ClassUtils.getDeclaredFieldValue(t, property);

				if (ObjectUtils.equals(constantPropValue, propValue)) {
					result = t;
					break;
				}
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
		return result;
	}

	/**
	 * 
	 * 从指定的枚举类中根据名称匹配指定值
	 * 
	 * @param <T>
	 * @param enumClass
	 * @param constantName
	 * @return
	 */
	private static <T extends Enum<T>> T fromEnumConstantName(Class<T> enumClass, String constantName) {
		T result = null;
		
		T[] enumConstants = enumClass.getEnumConstants();
		for (T t : enumConstants) {
			if (((Enum<?>) t).name().equals(constantName)) {
				result = t;
				break;
			}
		}
		return result;
	}

}
